export function initAgora() {
  return new Promise((resolve, reject) => {
    if (window.AgoraRTC) {
      resolve(window.AgoraRTC); // Web 环境
    } else if (window.plus) {
      // App 环境（示例：动态加载 SDK）
      const script = document.createElement("script");
      script.src = "https://your-cdn-path-to-agora-app-sdk.js";
      script.onload = () => resolve(window.AgoraAppSDK);
      script.onerror = () => reject(new Error("Failed to load Agora App SDK"));
      document.body.appendChild(script);
    } else {
      reject(new Error("Unsupported environment"));
    }
  });
}


export function initAgoraWeb() {
  if (!window.AgoraRTC) {
    throw new Error('Agora Web SDK 未加载，请检查CDN！');
  }
  
  const client = window.AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
  
  return {
    client,
    joinChannel: async (appId, channel, token, uid) => {
      await client.join(appId, channel, token, uid);
    },
    // 其他Web专用方法...
  };
}

export function initAgoraApp() {
  const agoraModule = uni.requireNativePlugin('Agora-RTC-Plugin');
  
  return {
    joinChannel: (appId, channel, token, uid) => {
      return new Promise((resolve, reject) => {
        agoraModule.joinChannel({
          appId,
          channel,
          token,
          uid
        }, (res) => {
          res.code === 0 ? resolve(res) : reject(res);
        });
      });
    },
    // 其他App专用方法...
  };
}

export function getAgoraInstance() {
  // 条件编译判断环境
  // #ifdef H5
  return initAgoraWeb();
  // #endif
  
  // #ifdef APP-PLUS
  return initAgoraApp();
  // #endif
  
  throw new Error('当前环境不支持Agora！');
}